package com.atguigu.spzx.manager.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.excel.EasyExcel;
import com.atguigu.spzx.common.exception.GuiguException;
import com.atguigu.spzx.common.utils.BeanUtils;
import com.atguigu.spzx.manager.entity.Category;
import com.atguigu.spzx.manager.listener.ExcelListener;
import com.atguigu.spzx.manager.mapper.CategoryMapper;
import com.atguigu.spzx.manager.service.CategoryService;
import com.atguigu.spzx.common.result.ResultCodeEnum;
import com.atguigu.spzx.manager.vo.category.CategoryExportExcelVo;
import com.atguigu.spzx.manager.vo.category.CategoryImportExcelVo;
import com.atguigu.spzx.manager.vo.category.CategoryQueryRespVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

/**
 * <p>
 * CategoryServiceImpl
 * </p>
 *
 * @author flyduck
 * @since 2023/10/28
 */
@Service
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    private CategoryMapper categoryMapper;

    /**
     * 分类列表，每次只查询一层数据
     * @param parentId
     * @return
     */
    @Override
    public List<CategoryQueryRespVo> getCategoryListByParentId(Long parentId) {
        //根据parentId查询 SELECT *  FROM category WHERE parent_id = 0;
        List<Category> categoryList = categoryMapper.getCategoryListByParentId(parentId);
        List<CategoryQueryRespVo> queryRespVos = BeanUtils.toBeanList(categoryList, CategoryQueryRespVo.class);

        //判断每个节点是否有下一层分类，如果有设置hasChildren为true
        if (CollectionUtil.isNotEmpty(queryRespVos)) {
            for (CategoryQueryRespVo respVo : queryRespVos) {
                Integer count = categoryMapper.getCategoryCountByParentId(respVo.getId());
                respVo.setHasChildren(count > 0 ? true : false);
            }
        }
        return queryRespVos;
    }

    /**
     * 导出数据
     * @param response
     */
    @Override
    public void exportCategoryList(HttpServletResponse response) {
        try {
            //1.设置响应头信息和其他信息
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");

            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("分类数据", "utf-8");

            //设置响应头
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");

            //2.调用方法查询所以分类
            List<Category> categoryList = categoryMapper.selectList(null);
            List<CategoryExportExcelVo> categoryExportExcelVos = BeanUtils.toBeanList(categoryList, CategoryExportExcelVo.class);

            //3.调用Excel的write方法完成写操作
            EasyExcel.write(response.getOutputStream(), CategoryExportExcelVo.class)
                    .sheet("分类数据")
                    .doWrite(categoryExportExcelVos);
        }catch (Exception e){
            throw new GuiguException(ResultCodeEnum.DATA_ERROR,e);
        }


    }

    /**
     * 导入数据
     * @param file
     */
    @Override
    public void importCategoryList(MultipartFile file) {
        try {
            //监听器
            ExcelListener<CategoryImportExcelVo> excelListener = new ExcelListener<CategoryImportExcelVo>(categoryMapper);
            EasyExcel.read(file.getInputStream(), CategoryImportExcelVo.class,excelListener)
                    .sheet()
                    .doRead();
        } catch (IOException e) {
            throw new GuiguException(ResultCodeEnum.DATA_ERROR,e);
        }
    }
}
